<?php
/**
 * 账单管理控制器
 * User: John
 * Date: 17-1-3
 * Time: 上午11:06
 */
namespace app\backend\controller;

use app\backend\controller\traits\AuthManager;
use app\backend\model\Building;
use app\backend\model\Contract;
use app\backend\model\Lease;
use app\backend\model\Member;
use app\backend\model\Trust;
use app\backend\model\WaterPower;
use think\Controller;
use app\backend\model\BillManager;
use think\Exception;

class BillManagerController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * 获取账单模型
     * @date   2017-3-14
     * @author wuhao
     *
     * @return BillManager
     */
    public function getBillModel()
    {
        static $model;
        if (!$model) {
            $model = new BillManager();
        }

        return $model;
    }

    /**
     * 获取租户应付账单
     * @date   2017-01-16
     * @author wuhao
     *
     * @param  string  $beginMonth   账单开始时间  201611
     * @param  string  $endMonth     账单结束时间  201612
     * @param  int     $status       结算状态
     * @param  int     $buildingId   楼宇id
     * @param  string  $room         房号
     * @param  int     $page         当前页
     * @param  int     $pageSize     每页个数
     *
     * @return json
     */
    public function leaseBill()
    {
        $beginMonth  = I('post.begin_month', '', 'strval');
        $endMonth    = I('post.end_month', '', 'strval');
        $status      = I('post.status', '', 'strval');
        $queryBuildingId  = I('post.building_id', '', 'intval');
        $room        = I('post.room', '', 'strval');
        $page        = I('post.page', 1, 'intval');
        $pageSize    = I('post.page_size', 15, 'intval');
        $buildModel = new Building();
        $leaseModel = new Lease();

        $thisMonth = date('Ym', time());//本月
        $nextMonth = date('Ym', strtotime('+1month'));//下月
        $thisTime = $thisMonth.'01';//本月第一天
        $thisEnd  = $thisMonth.date('t', strtotime($thisTime));//本月最后一天
        $nextTime = $nextMonth.'01';//下月第一天
        $nextEnd  = $nextMonth.date('t', strtotime($nextTime));//下月最后一天

        if ($beginMonth && $endMonth) {
            $begin = $beginMonth.'01';
            $endTmp = $endMonth.'01';
            $end   = $endMonth.date('t', strtotime($endTmp));
            if ((strtotime($begin) > strtotime($end))) {
                $this->apiReturn(400, [], '输入时间有误');
            }
            if (strtotime($begin) > strtotime($nextEnd)) {//搜索的开始时间比当前月+1月还大
                $this->apiReturn(400, [], '输入时间有误');
            }

            if ($endMonth > $thisMonth) {
                if ($this->_dtype != 2) {
                    //获取下个月信息
                    $end = $nextEnd;
                } else {
                    $end = $thisEnd;
                    //$endMonth = date('Ymd', time());
                }
            }
        } else {
            $begin = $thisTime;
            if ($this->_dtype != 2) {//默认查询到当前时间+1月
                $end = $nextEnd;
            } else {//默认查询到当前时间
                $end = $thisEnd;
                //$endMonth = date('Ymd', time());
            }
        }

        //@date 2017-07-10 员工查询房源范围内的账单
        if ($this->_dtype == 7) {
            $auth = $this->houseAuth($this->_memberId);
        } else {
            $auth = []; //其他不做限制
        }


        //获取账单列表
        $res = $this->getBillModel()->leaseBill($this->_pmid, $this->_pdtype, $this->_dtype, $begin, $end, $status, $queryBuildingId, $room, $auth, $page, $pageSize);
        if ($res) {
            $orderNums  = array_unique(array_column($res, 'contract_id'));

            //获取其他的基本信息
            $billInfo   = $this->getBillModel()->getPayBillInfo(['ordernum' => ['in', $orderNums], 'is_delete' => 0], 'ordernum, building_id, charge_out, begin_cycle, status');
            $buildingId = array_unique(array_column($billInfo, 'building_id'));
            //获取楼宇名称
            $buildingInfo = $buildModel->getBuildingList(['id' => ['in', $buildingId]], 'id, name');
            //获取对应的房源信息
            $houseNumbers = $leaseModel->getLeaseExtByOrderNum($orderNums, 'ordernum, house_number');

            $houseInfo = [];
            foreach ($houseNumbers as $a => $house) {
                $houseInfo[] = $house['house_number'];
            }
            $houseList = $buildModel->getHouseList(['house_number' => ['in', $houseInfo]], 'house_number, room');
            foreach ($res as $k =>  $v) {
                //获取每条账单对应的账单id数组
                $orderId = $this->getBillModel()->getBillDetailByOwner($this->_pmid, $this->_pdtype, $v['contract_id'], $v['begin_cycle'], $v['end_cycle'], $v['status'], 'id');
                $res[$k]['order_id'] = array_column($orderId, 'id');
                $res[$k]['total_money'] = yuan($v['total_money']);
                $res[$k]['room'] = '';
                //获取账单的对应的房源编号
                foreach ($houseNumbers as $number) {
                    if ($v['contract_id'] == $number['ordernum']) {
                        $res[$k]['house_number'][] = $number['house_number'];
                    }
                }
                //获取房源编号对应的房号
                foreach ($houseList as $h) {
                    if (in_array($h['house_number'], $res[$k]['house_number'])) {
                        $res[$k]['room'] .= $h['room'].',';
                    }
                }
                $res[$k]['room'] = rtrim($res[$k]['room'], ',');
                //获取账单的出账日期和楼宇id
                foreach ($billInfo as  $bill) {
                    if ($bill['ordernum'] == $v['contract_id'] && $bill['begin_cycle'] == $v['begin_cycle'] && $bill['status'] == $v['status']) {
                        $res[$k]['charge_out']  = $bill['charge_out'];
                        $res[$k]['building_id'] = $bill['building_id'];
                        break;
                    }
                }

                //获取对应的楼宇名称
                foreach ($buildingInfo as $build) {
                    if ($build['id'] == $res[$k]['building_id']) {
                        $res[$k]['name'] = $build['name'];
                        break;
                    }
                }
            }
            $sum   = $this->getBillModel()->countLeaseBill($this->_pmid, $this->_pdtype,$this->_dtype,  $begin, $end, $status, $queryBuildingId, $room, $auth);
            $total = ceil($sum / $pageSize);
            $data  = ['list' => $res, 'current_page' => $page, 'total' => $total];
            $this->apiReturn(200, $data, '');
        } else {
            $this->apiReturn(201, [], '没有数据');
        }
    }

    /**
     * 租户缴费页面--获取总金额
     * @date   2017-01-19
     * @author wuhao
     *
     * @param  string  $ordernum      合同编号
     * @param  string  $beginCycle    周期开始
     * @param  string  $endCycle      周期结束
     * @param  int     $status        结算状态
     * @param  array   $orderId       订单id数组
     *
     * @return json
     */
    public function getTotalMoney()
    {
        $ordernum      = I('post.ordernum', '', 'strval');
        $beginCycle    = I('post.begin_cycle', '', 'strval');
        $endCycle      = I('post.end_cycle', '', 'strval');
        $status        = I('post.status', 0, 'intval');
        $orderId       = I('post.order_id');
        $orderId       = json_decode($orderId, true);
        //$ordernum = '149500801179';$beginCycle='20150715';$endCycle='20150814';$status=0;$orderId=[3692, 3833, 3834];
        if (!$ordernum || !$beginCycle ||!$endCycle || $status !== 0 || !$orderId || !is_array($orderId)) {
            $this->apiReturn(400, [], '参数错误');
        }

        //判断租户应付的账单id数组是否正确
        $res = $this->getBillModel()->getBillDetailByOwner($this->_pmid, $this->_pdtype, $ordernum, $beginCycle, $endCycle, 0, 'id');
        if ($res) {
            $allOrderId = array_column($res, 'id');
            foreach ($orderId as $id) {
                if (!in_array($id, $allOrderId)) {
                    $this->apiReturn(400, [], '账单id有误!');
                }
            }
        } else {
            $this->apiReturn(400, [], '没有相应的账单!');
        }
        //获取租户要交费多少钱
        $data = $this->getBillModel()->getPayBillList(['id' => ['in', $orderId]], 'id, money, type_money, tenant_id');
        if (!$data) {
            $this->apiReturn(400, [], '没有相应的账单!');
        }

        $tenantId = $data[0]['tenant_id'];
        $waterFee = $houseFee = $powerFee = $propertyFee = $gtWaterFee = $gtPowerFee =  $totalFee = $taxFee = $other = 0;
        foreach ($data as $money) {
            if ($money['type_money'] == 1) {
                $houseFee += $money['money'];
            } elseif ($money['type_money'] == 2) {
                $propertyFee += $money['money'];
            } elseif ($money['type_money'] == 3) {
                $waterFee += $money['money'];
            } elseif ($money['type_money'] == 4) {
                $powerFee += $money['money'];
            } elseif ($money['type_money'] == 5) {
                $gtWaterFee += $money['money'];
            } elseif ($money['type_money'] == 6) {
                $gtPowerFee += $money['money'];
            } elseif ($money['type_money'] == 7) {
                $taxFee += $money['money'];
            } elseif ($money['type_money'] == 8) {//其他费用
                $other += $money['money'];
            }
        }

        $totalFee = $waterFee + $houseFee + $powerFee + $propertyFee + $gtWaterFee + $gtPowerFee + $taxFee + $other;
        $result   = [
            'house_fee'      => yuan($houseFee),
            'water_fee'      => yuan($waterFee),
            'property_fee'   => yuan($propertyFee),
            'power_fee'      => yuan($powerFee),
            'gt_water_fee'   => yuan($gtWaterFee),
            'gt_power_fee'   => yuan($gtPowerFee),
            'tax_fee'        => yuan($taxFee),
            'total_fee'      => yuan($totalFee),
            'other_fee'      => yuan($other),
            'begin_cycle'    => $beginCycle,
            'end_cycle'      => $endCycle,
            'mid'            => $tenantId,
            'ordernum'       => $ordernum,
            'order_id'       => $orderId,
        ];

        $this->apiReturn(200, $result, '');
    }

    /**
     * 查看应收租户账单明细
     * @date   2017-02-04
     * @author wuhao
     *
     * @param  string  $ordernum    合同编号
     * @param  string  $beginCycle  周期开始
     * @param  string  $endCycle    周期结束
     * @param  int     $status      结算状态
     * @return json
     */
    public function leaseBillDetail()
    {
        $ordernum   = I('post.id', '', 'strval');
        $beginCycle = I('post.begin_cycle', '', 'strval');
        $endCycle   = I('post.end_cycle', '', 'strval');
        //$status     = I('post.status', 0, 'intval');

        if (!$ordernum || !$beginCycle || !$endCycle) {
            $this->apiReturn(400, [], '参数错误');
        }

        $res = $this->getBillModel()->leaseBillDetail($ordernum, $beginCycle, $endCycle);
        if ($res) {
            $memberModel = new Member();
            //收费对象
            $ownerId = array_unique(array_column($res, 'owner_id'));
            //获取收费人信息
            $ownerInfo = $memberModel->getMemberInfoById($ownerId, 'id, nickname');
            foreach ($res as $k => $v) {
                foreach ($ownerInfo as $o) {
                    if ($o['id'] == $v['owner_id']) {
                        $res[$k]['owner_name'] = $o['nickname'];
                        break;
                    }
                }
                $res[$k]['free_money'] = yuan($v['free_money']);
                $res[$k]['money'] = yuan($v['money']);
            }

            //获取账单的备注
            $comment = $this->getBillModel()->getPayBillComment($ordernum, $beginCycle, $endCycle);
            $data = [
                'list'    => $res,
                'comment' => $comment,
            ];
            $this->apiReturn(200, $data, '');
        } else {
            $this->apiReturn(201, [], '没有数据');
        }
    }

    /**
     * 添加账单的费用信息
     * @date   2017-05-18
     * @author wuhao
     *
     * @param  string $id         合同编号
     * @param  int    $beginCycle 开始周期20150514
     * @param  int    $endCycle   结束周期20150514
     * @param  array  $array      要添加的数据
     * @param  string $comment    备注
     *
     * @return json
     */
    public function addPayBill()
    {
        if (!in_array($this->getOper('add_pay_bill'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $orderNum   = I('post.id', '', 'strval');
        $beginCycle = I('post.begin_cycle', '', 'intval');
        $endCycle   = I('post.end_cycle', '', 'intval');
        $array      = I('post.array');
        $comment    = I('post.comment', '', 'strval');
        $array      = json_decode($array, true);

        /*$orderNum = '149500801179';$beginCycle = 20150604; $endCycle=20150614;
        $array = [
            ['value'=>215,'type'=>3, 'bill_name' => '额外水费'],
            ['value'=>200,'type'=>4, 'bill_name' => '额外电费'],
            ['value'=>2000,'type'=>8, 'bill_name' => '其他费用'],
            ['value'=>1000,'type'=>9, 'bill_name' => '优惠'],
        ];*/

        if (!is_array($array) || !$array || !$orderNum || !$endCycle || !$beginCycle) {
            $this->apiReturn(400, [], '参数错误');
        }
        //$favorable = 0;//优惠金额
        $other = 0; //本次要添加的其他金额
        foreach ($array as $k => $v) {
            if (!$v) {
                $this->apiReturn(400, [], '参数错误');
            }
            if (!is_numeric($v['type']) || !is_numeric($v['value']) || !checkMoneyType($v['type']) || $v['value']<0) {
                $this->apiReturn(400, [], '参数错误');
            }

            $other += $v['value'];
        }

        //先获取应付账单基本信息
        $where = ['ordernum'=>$orderNum, 'begin_cycle'=>$beginCycle , 'end_cycle' =>$endCycle, 'status'=>0, 'is_delete' =>0];
        $baseInfo = $this->getBillModel()->getPayBillInfo($where);
        if (!$baseInfo) {
            $this->apiReturn(202, [], '没有相应的账单或账单已结算不能添加');
        }
        $baseInfo = $baseInfo[0];

        $addStatus = 1;
        foreach ($array as $a => $b) {
       /*     if ($b['type'] == 9) {//优惠金额保存负数
                $array[$a]['value'] = $b['value'] * -1;
            }*/

            $res = $this->getBillModel()->addPayBill($orderNum, $baseInfo['building_id'], $baseInfo['charge_out'], $baseInfo['type'], $baseInfo['begin_cycle'],
                $baseInfo['end_cycle'], $this->_pmid, $baseInfo['tenant_id'], fen($array[$a]['value']), $b['type'], $baseInfo['bill_time'], $b['bill_name']);
            if (!$res) {
                $addStatus = 0;
                zft_log('add_pay_bill', $this->getBillModel()->getLastSql());
            }
        }
        //}
        //新增备注
        if ($comment) {
            $status = $this->getBillModel()->addPayBillComment($orderNum, $beginCycle, $endCycle, $comment, $this->_pmid);
            if (!$status) {
                zft_log('add_pay_bill_comment', $this->getBillModel()->getLastSql());
            }
        }
        if ($addStatus == 0) {
            $this->apiReturn(200, [], '添加完成，存在失败的地方');
        } else {
            $this->apiReturn(200, [], '添加成功');
        }
    }

    /**
     * 添加账单的优惠金额
     * @date   2017-06-19
     * @author wuhao
     *
     * @param  int    $id         账单id
     * @param  float  $money      优惠的金额
     *
     * @return json
     */
    public function addDiscount()
    {
        if (!in_array($this->getOper('add_discount'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $id        = I('post.id', '', 'intval');
        $freeMoney = I('post.free_money', '', 'floatval');
        //$id=4075;$freeMoney=600;
        if (!$id || !is_numeric($id)) {
            $this->apiReturn(400, [], '账单id有误');
        }
        if (!$freeMoney || !is_numeric($freeMoney) || $freeMoney<=0) {
            $this->apiReturn(400, [], '优惠金额有误');
        }
        $freeMoney    = fen($freeMoney);//转化为分
        $billInfoList = $this->getBillModel()->getPayBillList(['id'=>$id, 'status'=>0]);
        if (!$billInfoList) {
            $this->apiReturn(202, [], '没有相应的账单或账单已结算不能添加');
        }
        $billInfo = $billInfoList[0];
        if ($billInfo['owner_id'] != $this->_pmid) {
            $this->apiReturn(202, [], '非收款方,不能添加');
        }
        $discountMoney = $billInfo['free_money'];//优惠金额
        $money         = $billInfo['money'];     //实收金额
        if ($money < $freeMoney) {
            $this->apiReturn(202, [], '优惠金额不能大于实收的金额');
        }
        //更新这个账单
        $update = $this->getBillModel()->updatePayBill(['id'=>$id], ['free_money' => $discountMoney+$freeMoney, 'money' => $money-$freeMoney]);
        if (!$update) {
            zft_log('add_pay_bill', $this->getBillModel()->getLastSql());
            $this->apiReturn(201, [], '添加优惠金额失败');
        } else {
            $this->apiReturn(200, [], '添加成功');
        }
    }



    /**
     * 租赁账单获取人工确认收款的对应信息
     * @date   2017-05-22
     * @author wuhao
     *
     * @param  string $ordernum   合同编号
     * @param  int    $beginCycle 开始周期20150514
     * @param  int    $endCycle   结束周期20150514
     *
     * @return json
     */
    public function getManualCollection()
    {
        if (!in_array($this->getOper('manual_collection'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $ordernum   = I('post.ordernum', '', 'string');
        $beginCycle = I('post.begin_cycle', '', 'intval');
        $endCycle   = I('post.end_cycle', '', 'intval');
        //$ordernum='149500801179';$beginCycle='20150715';$endCycle='20150814';
        if (!$ordernum) {
            $this->apiReturn(400, [], '账单号有误');
        }
        if (!$beginCycle || !$endCycle) {
            $this->apiReturn(400, [], '账单周期有误');
        }
        //获取这个用户应收明细
        $billDetail = $this->getBillModel()->getBillDetailByOwner($this->_pmid, $this->_pdtype,  $ordernum, $beginCycle, $endCycle, 0,
            'ordernum, begin_cycle, end_cycle, tenant_id, building_id, id,  money, type_money');
        if (!$billDetail) {
            $this->apiReturn(202, [], '没有相应的账单');
        }
        //获取房号信息
        $leaseModel = new Lease();
        $houseInfo  = $leaseModel->getLeaseExtByOrderNum($ordernum, 'room');
        $roomArray = array_column($houseInfo, 'room');

        //获取位置信息
        $buildingId   = $billDetail[0]['building_id'];
        $buildModel   = new Building();
        $buildingInfo = $buildModel->getBuildingInfo($buildingId, 'province, city, country, address');

        //获取租户信息
        $tenantId    = $billDetail[0]['tenant_id'];
        $memberModel = new Member();
        $tenantInfo  = $memberModel->getMemberInfoById($tenantId, 'id, nickname');

        //账单周期
        $beginCycle = $billDetail[0]['begin_cycle'];
        $endCycle   = $billDetail[0]['end_cycle'];

        //总金额
        $money = 0;
        //金额内容
        $content = [];
        $orderId = array_column($billDetail, 'id');
        foreach ($billDetail as $k => $v) {
            $money += $v['money'];
            $content[] = [
                'money'      => ($v['type_money'] == 9) ? (yuan($v['money'] * (-1))) : yuan($v['money']), //判断是否是优惠金额
                'type_money' => $v['type_money'],
            ];

        }

        $data = [
            'province'    => $buildingInfo['province'],
            'city'        => $buildingInfo['city'],
            'country'     => $buildingInfo['country'],
            'address'     => $buildingInfo['address'],
            'nickname'    => $tenantInfo['nickname'],
            'tenant_id'   => $tenantInfo['id'],
            'order_id'    => $orderId,
            'room'        => $roomArray,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'detail'      => $content,
            'total_money' => yuan($money),
        ];

        $this->apiReturn(200, $data, '');
    }

    /**
     * 租赁账单--人工确认收款设置
     * @date   2017-05-23
     * @author wuhao
     *
     * @param  string $ordernum     合同编号
     * @param  int    $beginCycle   开始周期20150514
     * @param  int    $endCycle     结束周期20150514
     * @param  array  $orderId      账单id数组
     * @param  int    $payType      支付方式
     * @param  string $serialNumber 流水号
     * @param  int    $payTime      支付时间
     *
     * @return json
     */
    public function setManualCollection()
    {
        if (!in_array($this->getOper('manual_collection'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $ordernum     = I('post.ordernum', '', 'string');
        $beginCycle   = I('post.begin_cycle', '', 'intval');
        $endCycle     = I('post.end_cycle', '', 'intval');
        $orderId      = I('post.order_id');
        $payType      = I('post.pay_type', '', 'intval');
        $serialNumber = I('post.serial_number', '', 'strval');
        $payTime      = I('post.pay_time', '', 'intval');

        //$ordernum='149500801179';$beginCycle='20150715';$endCycle='20150814';$orderId = [3692,3833,3834,3835];$payType=1;$serialNumber='sd234343546657';$payTime='20170505';
        $orderId     = json_decode($orderId, true);
        $allPayTypes = [0, 1, 2, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314];
        if (!$ordernum || !$beginCycle || !$endCycle || !$orderId || !is_array($orderId)) {
            $this->apiReturn(400, [], '所传参数有误');
        }
        if (!is_numeric($payType) || !in_array($payType, $allPayTypes)) {
            $this->apiReturn(400, [], '支付方式有误');
        }
        if ($payType != 0 && !$serialNumber) {
            $this->apiReturn(400, [], '流水号不能为空');
        }
        if (!$payTime) {
            $this->apiReturn(400, [], '支付时间有误');
        }
        //获取这个用户应收账单的id
        $idArr = $this->getBillModel()->getBillDetailByOwner($this->_pmid, $this->_pdtype, $ordernum, $beginCycle, $endCycle, 0, 'id');
        if (!$idArr) {
            $this->apiReturn(202, [], '找不到对应账单');
        }
        $orderArray = array_column($idArr, 'id');
        //判断所传账单id数组是否在该用户的应收id里
        foreach ($orderId as $id) {
            if (!in_array($id, $orderArray)) {
                $this->apiReturn(203, [], '账单id有误');
            }
        }
        $res = $this->getBillModel()->addManualCollectionRecord($orderId, $payType, $serialNumber, $payTime, $this->_pmid);
        if ($res['code'] == 200) {
            $this->apiReturn($res['code'], [], $res['msg']);
        } elseif ($res['code'] == 400) {
            $this->apiReturn($res['code'], [], $res['msg']);
        } else {
            zft_log('manual_collection', $res['msg']);
            $this->apiReturn($res['code'], [], '确认收款失败');
        }
    }

    /**s
     * 获取托管应付账单
     * @date   2017-01-24
     * @author wuhao
     *
     * @param  int  $beginMonth   账单开始时间  201611
     * @param  int  $endMonth     账单结束时间  201612
     * @param  string  $name      业主名称
     * @param  string  $mobile    业主电话
     * @param  int  $status       结算状态
     * @param  int  $page         当前页
     * @param  int  $pageSize     每页个数
     * @param  int  $total        总数
     *
     * @return json
     */
    public function trustPayBill()
    {
        if (!in_array($this->getOper('trust_pay'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $beginMonth  = I('post.begin_month', '', 'intval');
        $endMonth    = I('post.end_month', '', 'intval');
        $name        = I('post.name', '', 'strval');
        $mobile      = I('post.mobile', '', 'strval');
        $status      = I('post.status', '', 'strval');
        $page        = I('post.page', 1, 'intval');
        $pageSize    = I('post.page_size', 15, 'intval');

        if (!is_numeric($page) || !is_numeric($pageSize)) {
            $this->apiReturn(400, [], '参数错误');
        }

        if (strtotime($beginMonth) && strtotime($endMonth)) {
            $beginMonth .= '01';
            $endTmp = $endMonth.'01';
            $endMonth   .= date('t', strtotime($endTmp));
            if ((strtotime($beginMonth) > strtotime($endMonth)) || strtotime($beginMonth) > time()) {
                $this->apiReturn(400, [], '输入时间有误');
            }
            if (strtotime($endMonth) > time()) {
                $endMonth = date('Ymd', time());
            }
        } else {
            //默认查询到当前时间
            $endMonth = date('Ymd', time());
        }

        $buildModel = new Building();
        $res = $this->getBillModel()->getTrustPayBill($this->_pmid, $this->_pdtype, $beginMonth, $endMonth, $name, $mobile, $status, $page, $pageSize);
        if ($res) {
            $buildingId = array_unique(array_column($res['list'], 'building_id'));
            $buildingInfo = $buildModel->getBuildingList(['id' => ['in', $buildingId]], 'id, name');
            foreach ($res['list'] as $k => $v) {
                //应收租金和应收分成金额  /100
                $res['list'][$k]['should_rent'] = yuan($v['should_rent']);
                $res['list'][$k]['share_money'] = yuan($v['share_money']);
                if ($v['status'] === 0) {
                    //未结算状态的应付和实付
                    $res['list'][$k]['should_pay'] = $res['list'][$k]['should_rent'] - $res['list'][$k]['share_money'];
                    $res['list'][$k]['real_pay']   = 0;
                } else {
                    //已结算
                    $res['list'][$k]['should_pay'] = $res['list'][$k]['should_rent'] - $res['list'][$k]['share_money'];
                    $res['list'][$k]['real_pay']   = $res['list'][$k]['should_rent'] - $res['list'][$k]['share_money'];
                }
                unset($res['list'][$k]['should_rent']);
                unset($res['list'][$k]['share_money']);
                //获取楼宇名字
                foreach ($buildingInfo as $build) {
                    if ($build['id'] == $v['building_id']) {
                        $res['list'][$k]['name'] = $build['name'];
                        break;
                    }
                }

                //获取门牌号
                $houseInfo = $buildModel->getHouseRoom($v['building_id'], $v['owner_id']);
                $res['list'][$k]['room'] = '';
                if (!$houseInfo) {
                    $res['list'][$k]['room'] = '';
                } else {
                    foreach ($houseInfo as $a => $b) {
                        $res['list'][$k]['room'] .= $b['room'].',';
                    }
                    $res['list'][$k]['room'] = rtrim($res['list'][$k]['room'], ',');
                }
            }
            $this->apiReturn(200, $res, '');
        } else {
            $this->apiReturn(400, [], '没有数据');
        }
    }

    /**
     * 托管缴费页面--获取总金额
     * @date   2017-01-24
     * @author wuhao
     *
     * @param  string  $id          合同编号
     * @param  string  $beginCycle  周期开始
     * @param  string  $endCycle    周期结束
     * @param  int     $status      结算状态
     *
     * @return json
     */
    public function trustPayTotal()
    {
        if (!in_array($this->getOper('trust_pay'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $id            = I('post.id', '', 'strval');
        $beginCycle    = I('post.begin_cycle', '', 'strval');
        $endCycle      = I('post.end_cycle', '', 'strval');
        $status        = I('post.status', 0, 'intval');
        //$id = "20170124464611109";
        if (!$id ||!$beginCycle|| !$endCycle || $status !== 0) {
            $this->apiReturn(400, [], '参数错误');
        }

        $res = $this->getBillModel()->trustPayTotal($id, $this->_pmid, $this->_pdtype, $beginCycle, $endCycle, $status);
        if ($res) {
            $res['should_pay'] = yuan($res['should_rent']) - yuan($res['share_money']);
            unset($res['should_rent']);
            unset($res['share_money']);
            $this->apiReturn(200, $res, '');
        } else {
            $this->apiReturn(400, [], '没有数据');
        }
    }

    /**
     * 获取应收托管账单
     * @date   2017-01-24
     * @author wuhao
     *
     * @param  int     $beginMonth   账单开始时间  201611
     * @param  int     $endMonth     账单结束时间  201612
     * @param  int     $status       结算状态
     * @param  string  $name         托管公司姓名
     * @param  string  $mobile       托管公司电话
     * @param  int     $page         当前页
     * @param  int     $page_size    每页个数
     *
     * @return json
     */
    public function trustIncomeBill()
    {
        if (!in_array($this->getOper('trust_income'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $beginMonth  = I('post.begin_month', '', 'strval');
        $endMonth    = I('post.end_month', '', 'strval');
        $status      = I('post.status', '', 'strval');
        $tname       = I('post.name', '', 'strval');
        $mobile      = I('post.mobile', '', 'strval');
        $page        = I('post.page', 1, 'intval');
        $pageSize    = I('post.page_size', 15, 'intval');

        if (!is_numeric($page) || !is_numeric($pageSize)) {
            $this->apiReturn(400, [], '参数错误');
        }

        if (!empty($beginMonth) && !empty($endMonth)) {
            $beginMonth .= '01';
            $endTmp = $endMonth.'01';
            $endMonth   .= date('t', strtotime($endTmp));
            if ((strtotime($beginMonth) > strtotime($endMonth)) || strtotime($beginMonth) > time()) {
                $this->apiReturn(400, [], '输入时间有误');
            }
            if (strtotime($endMonth) > time()) {
                $endMonth = date('Ymd', time());
            }
        } else {
            //默认查询到当前时间
            $endMonth = date('Ymd', time());
        }

        $buildModel = new Building();
        $res = $this->getBillModel()->getTrustIncomeBill($this->_pmid, $this->_pdtype, $tname, $mobile, $beginMonth, $endMonth, $status, $page, $pageSize);
        if ($res) {
            foreach ($res['list'] as $k => $v) {
                //获取各种费用
                $res['list'][$k]['should_get']  = yuan($v['should_rent']) -  yuan($v['share_money']);
                $res['list'][$k]['real_rent'] = yuan($v['real_rent']);
                if ($v['status'] == 0) {
                    //未支付实收费用为0
                    $res['list'][$k]['real_get'] = 0;
                } else {
                    $res['list'][$k]['real_get'] = yuan($v['should_rent']) -  yuan($v['share_money']);
                }
                //获取楼宇名字
                $name = $buildModel->getBuildingName($v['building_id']);
                if ($name) {
                    $res['list'][$k]['name'] = $name['name'];
                }
                unset($res['list'][$k]['should_rent']);
                unset($res['list'][$k]['share_money']);

                //获取门牌号
                $houseInfo = $buildModel->getHouseRoom($v['building_id'], $v['owner_id']);
                $res['list'][$k]['room'] = '';
                if (!$houseInfo) {
                    $res['list'][$k]['room'] = '';
                } else {
                    foreach ($houseInfo as $a => $b) {
                        $res['list'][$k]['room'] .= $b['room'].',';
                    }
                    $res['list'][$k]['room'] = rtrim($res['list'][$k]['room'], ',');
                }
            }

            $this->apiReturn(200, $res, '');
        } else {
            $this->apiReturn(400, [], '没有数据');
        }
    }

    /**
     * 获取账单的支付状态
     * @date   2017-2-8
     * @author wuhao
     *
     * @param  string  $orderNum         订单号
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @param  int     $type             缴费类型：1租赁账单，2托管账单
     *
     * @return json
     */
    public function getPayStatus()
    {
        $orderNum      = I('post.order_num', '', 'strval');
        $beginCycle    = I('post.begin_cycle', '', 'intval');
        $endCycle      = I('post.end_cycle', '', 'intval');
        $type          = I('post.type', '', 'intval');

        //$orderNum='461110501';$beginCycle='20161223';$endCycle='20170122';$type=1;
        if (!$orderNum || !$beginCycle || !$endCycle || !in_array($type, [1, 2])) {
            $this->apiReturn(400, [], '参数错误');
        }

        if ($type == 1) {
            $res = $this->getBillModel()->payBillStatus($orderNum, $beginCycle, $endCycle);
        } else {
            $res = $this->getBillModel()->trustBillStatus($orderNum, $beginCycle, $endCycle);
        }

        if (!$res) {
            $this->apiReturn(401, [], '账单不存在');
        } else {
            $status = ['status' => $res['status']];
            $this->apiReturn(200, $status, '');
        }
    }

    /**
     * 收入管理 - 收款列表获取
     * @date   2017-3-23
     * @author wuhao
     *
     * @param  string  $time     时间
     * @param  int     $page     页数
     * @param  int     $pageSize 每页个数
     * @param  int     $excel    是否导出 1=是 0=否
     *
     * @return json
     */
    public function incomeManager()
    {
        if (!in_array($this->_pdtype, [1, 3, 4, 5, 6])) {
            $this->apiReturn(400, [], '无权操作');
        }
        $time     = I('time', '', 'strval');
        $page     = I('page', 1, 'intval');
        $pageSize = I('page_size', 10, 'intval');
        $buildingId = I('building_id', '', 'intval');
        $excel    = I('excel', 0, 'intval');
        //$time     = '201702';$excel=1;
        if (!strtotime($time) || !$pageSize || !$page) {
            $this->apiReturn(400, [], '参数错误');
        }

        if ($excel == 1) {
            //导出查询全部
            $bills = $this->getBillModel()->getLeaseIncomeBill($this->_pmid,$time,$buildingId, false);
        } else {
            $bills = $this->getBillModel()->getLeaseIncomeBill($this->_pmid,$time, $buildingId, true, $page, $pageSize);
        }

        if (!$bills) {
            $this->apiReturn(201, [], '没有数据');
        }
        $buildModel = new Building();
        $leaseModel = new Lease();
        $memberModel = new Member();
        //获取楼宇id
        $buildId = array_unique(array_column($bills['list'], 'building_id'));
        //租户id
        $tenantId = array_unique(array_column($bills['list'], 'tenant_id'));

        //获取楼宇名称
        $buildName = $buildModel->getBuildingList(['id' => ['in', $buildId]], 'id, name');
        //获取租户信息
        $tenantInfo = $memberModel->getMemberInfo(['id' => ['in', $tenantId]], 'id, nickname, mobile');

        //合同编号数组
        $orderNum = array_unique(array_column($bills['list'], 'ordernum'));

        //获取房源编号
        $houseNumber = $leaseModel->getLeaseExtByOrderNum($orderNum, 'ordernum, house_number');
        $numbers = array_column($houseNumber, 'house_number');
        //获取对应的房源信息
        $houseInfo  = $buildModel->getHouseList(['house_number' => ['in', $numbers]], 'house_number, room');

        //获取合同到期时间
        $expire = $leaseModel->getContractInfo(['ordernum' => ['in', $orderNum]], 'ordernum, end_time');

        foreach ($bills['list'] as $key => $val) {
            $bills['list'][$key]['money']       = yuan($val['money']);
            $bills['list'][$key]['charge_out']  = date('Y-m-d', strtotime($val['charge_out']));
            $bills['list'][$key]['begin_cycle'] = date('Y-m-d', strtotime($val['begin_cycle']));
            $bills['list'][$key]['end_cycle']   = date('Y-m-d', strtotime($val['end_cycle']));
            //楼宇名称
            foreach ($buildName as $build) {
                if ($build['id'] == $val['building_id']) {
                    $bills['list'][$key]['name'] = $build['name'];
                }
            }
            //门牌号
            $bills['list'][$key]['room'] = '';
            foreach ($houseNumber as $number) {
               if ($number['ordernum'] == $val['ordernum']) {
                   foreach ($houseInfo as $h) {
                       if ($h['house_number'] == $number['house_number']) {
                           $bills['list'][$key]['room'] .= $h['room'].',';
                       }
                   }
               }
            }
            $bills['list'][$key]['room'] = rtrim($bills['list'][$key]['room'], ',');

            //获取现在距离合同的到期时间
            foreach ($expire as $e) {
                if ($e['ordernum'] == $val['ordernum']) {
                    $bills['list'][$key]['expire']    = date('Y-m-d', strtotime($e['end_time']));
                    $bills['list'][$key]['countdown'] = round((strtotime($e['end_time']) - time()) / 86400);
                }
            }

            //租户姓名电话
            foreach ($tenantInfo as $t) {
                if ($t['id'] == $val['tenant_id']) {
                    $bills['list'][$key]['username']  = $t['nickname'];
                    $bills['list'][$key]['mobile']    = $t['mobile'];
                }
            }
        }

        if ($excel == 1) {
            $this->_exportIncomeData($bills['list'], $time. '-收款账单');
        } else {
            $this->apiReturn(200, $bills, '');
        }

    }

    /**
     * 收入管理 - 收款统计
     * @date   2017-3-24
     * @author wuhao
     *
     * @param  string  $time     时间
     * @param  int  $buildingId  楼宇id
     *
     * @return json
     */
    public function incomeManagerSummary()
    {
        if (!in_array($this->_pdtype, [1, 3, 4, 5, 6])) {
            $this->apiReturn(400, [], '无权操作');
        }

        $time     = I('post.time', '', 'strval');
        $buildingId = I('post.building_id', '', 'intval');
        //$time='201702';
        if (!strtotime($time)) {
            $this->apiReturn(400, [], '参数错误');
        }

        if ($buildingId) {
            $where = ['owner_id' => $this->_pmid, 'bill_time' => $time, 'building_id' => $buildingId, 'is_delete' =>0];
        } else {
            $where = ['owner_id' => $this->_pmid, 'bill_time' => $time, 'is_delete' =>0];
        }

        $bills     = $this->getBillModel()->getPayBillList(
            $where,
            'ordernum, begin_cycle, end_cycle, tenant_id, money, status');
        if (!$bills) {
            $this->apiReturn(201, [], '没有数据');
        }

        $totalMoney = $payedMoney = $unPayedMoney = 0;
        $unPayedId = $payedId = [];
        foreach ($bills as $k => $v) {
            if ($v['status'] == 1) {
                $payedId[] = $v['ordernum'].$v['begin_cycle'].$v['end_cycle'];
                $payedMoney += $v['money'];
            } else {
                $unPayedId[] = $v['ordernum'].$v['begin_cycle'].$v['end_cycle'];
                $unPayedMoney += $v['money'];
            }
        }
        $countId = array_merge($payedId, $unPayedId);

        //var_dump($payedMoney, $unPayedMoney);die;

        $totalMoney   = yuan($payedMoney + $unPayedMoney);//总金额
        $payedMoney   = yuan($payedMoney);//已收金额
        $unPayedMoney = yuan($unPayedMoney);//未收金额

        $data = [
            'count'         => count(array_unique($countId)),
            'count_payed'   => count(array_unique($payedId)),
            'count_unpayed' => count(array_unique($unPayedId)),
            'total_money'   => $totalMoney,
            'payed_money'   => $payedMoney,
            'unpayed_money' => $unPayedMoney,
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 收入管理 - 收款列表数据导出
     * @date   2017-3-24
     * @author wuhao
     *
     * @param  array  $data     数据
     * @param  string $fileName 导出文件名
     *
     * @return json
     */
    private function _exportIncomeData(array $data, $fileName = '')
    {
        if (!$fileName) {
            $fileName = date('Y-m-d');
        }
        if (!$data) {
            exit('没有数据');
        }

        $objPHPExcel = load_excel();
        $objWriter   = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($fileName);
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);

        $objPHPExcel->getActiveSheet()->setCellValue('A1', '合同编号');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '楼宇名称');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '门牌号');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '倒计时');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '租户');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '联系电话');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '出账日期');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '到期时间');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '账单周期');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '金额');
        $objPHPExcel->getActiveSheet()->setCellValue('K1', '结算状态');

        $num = 2;
        foreach ($data as $key => $value) {
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$num, $value['ordernum'] . ' ');
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$num, $value['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$num, $value['room']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.$num, $value['countdown']);
            $objPHPExcel->getActiveSheet()->setCellValue('E'.$num, $value['username']);
            $objPHPExcel->getActiveSheet()->setCellValue('F'.$num, $value['mobile']);
            $objPHPExcel->getActiveSheet()->setCellValue('G'.$num, $value['charge_out']);
            $objPHPExcel->getActiveSheet()->setCellValue('H'.$num, $value['expire']);
            $objPHPExcel->getActiveSheet()->setCellValue('I'.$num, $value['begin_cycle'] . ' ~ ' . $value['end_cycle']);
            $objPHPExcel->getActiveSheet()->setCellValue('J'.$num, $value['money']);
            $objPHPExcel->getActiveSheet()->setCellValue('K'.$num, ($value['status']) == 1 ? '已结算' : '未结算');
            ++$num;
        }

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename='.$fileName.'.xls');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    /**
     * 收入管理 - 付款列表获取
     * @date   2017-3-27
     * @author wuhao
     *
     * @param  string  $time     时间-201702
     * @param  int     $page     页数
     * @param  int     $pageSize 每页个数
     * @param  int     $excel    是否导出 1=是 0=否
     *
     * @return json
     */
    public function payManager()
    {
        if (!in_array($this->_pdtype, [3, 4])) {
            $this->apiReturn(400, [], '无权操作');
        }

        $time     = I('time', '', 'strval');
        $buildingId = I('building_id', '', 'intval');
        $page     = I('page', 1, 'intval');
        $pageSize = I('page_size', 10, 'intval');
        $excel    = I('excel', 0, 'intval');
        //$time     = '201702';$excel=1;
        if (!strtotime($time) || !$pageSize || !$page) {
            $this->apiReturn(400, [], '参数错误');
        }

        if ($buildingId) {
            $where = ['tenant_id' => $this->_pmid, 'pay_bill_time' => $time, 'building_id' => $buildingId, 'is_delete' => 0];
        } else {
            $where = ['tenant_id' => $this->_pmid, 'pay_bill_time' => $time, 'is_delete' => 0];
        }
        $offset = ($page - 1) * $pageSize;
        if ($excel == 1) {
            $bills = $this->getBillModel()->getAllTrustBill(
                $where,
                'owner_id, tenant_id, ordernum, rent_rate, should_rent, real_rent, share_money, real_share_money, building_id, status');

        } else {
            $bills = $this->getBillModel()->getTrustBill(
                $where,
                'owner_id, tenant_id, ordernum, rent_rate, should_rent, real_rent, share_money, real_share_money, building_id, status', $offset, $pageSize);
        }
        if (!$bills) {
            $this->apiReturn(201, [], '没有数据');
        }
        $buildingModel = new Building();
        foreach ($bills as $k => $bill) {
            //金额转为元
            $bills[$k]['should_rent']      = yuan($bill['should_rent']);
            $bills[$k]['real_rent']        = yuan($bill['real_rent']);
            $bills[$k]['share_money']      = yuan($bill['share_money']);
            $bills[$k]['real_share_money'] = yuan($bill['real_share_money']);

            //应付房东,已付房东
            $bills[$k]['pay']      = yuan($bill['should_rent'] - $bill['share_money']);
            $bills[$k]['real_pay'] = yuan($bill['real_rent'] - $bill['real_share_money']);

            //获取楼宇的基本信息
            $buildingInfo = $buildingModel->getBuildingDetail($bill['building_id'],
                'name, province, city, country, trade_area');
            if ($buildingInfo) {
                $bills[$k]['name']       = $buildingInfo['name'];
                $bills[$k]['province']   = $buildingInfo['province'];
                $bills[$k]['city']       = $buildingInfo['city'];
                $bills[$k]['country']    = $buildingInfo['country'];
                $bills[$k]['trade_area'] = $buildingInfo['trade_area'];
                unset($buildingInfo);
            } else {
                $bills[$k]['name']       = '';
                $bills[$k]['province']   = '';
                $bills[$k]['city']       = '';
                $bills[$k]['country']    = '';
                $bills[$k]['trade_area'] = '';
            }

            //获取业主托管的房源的信息
            $trustHouse = $buildingModel->getHouseList(['mid' => $bill['owner_id'], 'building_id' => $bill['building_id'], 'trust_status' => 1, 'is_delete'=>0],
                'area, status');
            if ($trustHouse) {
                $rentArea = $totalArea = 0;
                foreach ($trustHouse as $key => $house) {
                    if ($house['status'] == 1) {//出租中
                        $rentArea += $house['area'];
                    }
                    $totalArea += $house['area'];
                }
                $bills[$k]['rent_area']  = $rentArea;
                $bills[$k]['total_area'] = $totalArea;
                unset($rentArea, $totalArea, $trustHouse);
            } else {
                $bills[$k]['rent_area']  = 0;
                $bills[$k]['total_area'] = 0;
            }
        }

        if ($excel == 1) {
            $this->_exportPayData($bills,time() . '付款账单');
        } else {
            $count = $this->getBillModel()->cntTrustBill(
                ['tenant_id' => $this->_pmid, 'pay_bill_time' => $time, 'building_id' => $buildingId],
                'owner_id, tenant_id, ordernum, rent_rate, should_rent, real_rent, share_money, real_share_money, building_id, status');
            $total = ceil($count / $pageSize);
            $data  = [
                'list'  => $bills,
                'total' => $total,
                'page'  => $page,
            ];
            $this->apiReturn(200, $data, '');
        }
    }

    /**
     * 收入管理 - 付款统计
     * @date   2017-3-27
     * @author wuhao
     *
     * @param  string  $time     时间
     *
     * @return
     */
    public function incomePaySummary()
    {
        if (!in_array($this->_pdtype, [3, 4])) {
            $this->apiReturn(400, [], '无权操作');
        }

        $time     = I('post.time', '', 'strval');
        $buildingId = I('building_id', '', 'intval');
        //$time='201702';
        if (!strtotime($time)) {
            $this->apiReturn(400, [], '参数错误');
        }

        if ($buildingId) {
            $where = ['tenant_id' => $this->_pmid, 'pay_bill_time' => $time, 'building_id' => $buildingId, 'is_delete' => 0];
        } else {
            $where = ['tenant_id' => $this->_pmid, 'pay_bill_time' => $time,  'is_delete' => 0];
        }
        $bills = $this->getBillModel()->getAllTrustBill(
            $where,
            'owner_id, tenant_id, ordernum, rent_rate, should_rent, real_rent, share_money, real_share_money, building_id, status');
        if (!$bills) {
            $this->apiReturn(201, [], '没有数据');
        }
        //获取截止上月欠费费用
        $overdue = $this->getBillModel()->getAllTrustBill(
            ['tenant_id' => $this->_pmid, 'pay_bill_time' => ['lt', date('Ym')], 'building_id' => $buildingId, 'status' => 0,  'is_delete' => 0],
            'should_rent-share_money as money');
        //截止上月欠费和户数
        $overdueMoney = $overdueCount = 0;
        if ($overdue) {//有欠费的
            foreach ($overdue as $k => $v) {
                $overdueMoney += $v['money'];
            }
            $overdueMoney = yuan($overdueMoney);
            $overdueCount = count($overdue);
        }

        $buildingModel = new Building();
        //应得分成户数,实得分成户数,应付房东户数,实付房东户数
        $rentCount = $realRentCount = $payCount = $realPayCount = 0;
        //应得分成金额,已得分成金额,应付房东金额,已付房东金额
        $shouldGet = $realGet = $payMoney = $realPayMoney = 0;
        foreach ($bills as $key => $bill) {
            $cnt = $buildingModel->getRentHouseCnt($bill['building_id'], $bill['owner_id'], 1, 1);//获取这个业主在这栋楼的已出租已托管的房源
            if ($cnt) {
                $rentCount += $cnt['cnt'];
                if ($bill['real_rent'] != 0) {//实际分成不为0,也就是租付都付清了
                    $realRentCount += $cnt['cnt'];
                }
            }
            //应付房东和已付房东个数计算
            if ($bill['status'] == 1) {
                ++$realPayCount;
            }
            ++$payCount;
            //应得分成金额
            $shouldGet += $bill['share_money'];
            //已得分成金额
            $realGet   += $bill['real_share_money'];
            //应付房东金额
            $payMoney  += ($bill['should_rent'] - $bill['share_money']);
            //实付房东金额
            if ($bill['status'] == 1) {
                $realPayMoney += ($bill['should_rent'] - $bill['share_money']);
            }
        }

        //转化为元
        $shouldGet    = yuan($shouldGet);
        $realGet      = yuan($realGet);
        $payMoney     = yuan($payMoney);
        $realPayMoney = yuan($realPayMoney);
        $data         = [
            'rent_count'     => $rentCount,
            'should_get'     => $shouldGet,
            'real_count'     => $realRentCount,
            'real_get'       => $realGet,
            'pay_count'      => $payCount,
            'pay_money'      => $payMoney,
            'real_pay_count' => $realPayCount,
            'real_pay_money' => $realPayMoney,
            'overdue_count'  => $overdueCount,
            'overdue_money'  => $overdueMoney
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 收入管理 - 付款列表数据导出
     * @date   2017-3-27
     * @author wuhao
     *
     * @param  array  $data     数据
     * @param  string $fileName 导出文件名
     *
     * @return
     */
    private function _exportPayData(array $data, $fileName = '')
    {
        if (!$fileName) {
            $fileName = date('Y-m-d');
        }
        if (!$data) {
            exit('没有数据');
        }

        $objPHPExcel = load_excel();
        $objWriter   = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($fileName);
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);

        $objPHPExcel->getActiveSheet()->setCellValue('A1', '楼宇名称');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '区域');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '商圈');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '托管模式');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '出租率');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '应得分成');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '已得分成');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '应付房东');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '已付房东');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '总面积');
        $objPHPExcel->getActiveSheet()->setCellValue('K1', '已出租面积');

        $num = 2;
        foreach ($data as $key => $value) {
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$num, $value['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$num, $value['city']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$num, $value['trade_area']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.$num, '保底分成');
            $objPHPExcel->getActiveSheet()->setCellValue('E'.$num, $value['rent_rate']);
            $objPHPExcel->getActiveSheet()->setCellValue('F'.$num, $value['share_money']);
            $objPHPExcel->getActiveSheet()->setCellValue('G'.$num, $value['real_share_money']);
            $objPHPExcel->getActiveSheet()->setCellValue('H'.$num, $value['should_rent'] - $value['share_money']);
            $objPHPExcel->getActiveSheet()->setCellValue('I'.$num, $value['real_rent'] - $value['real_share_money']);
            $objPHPExcel->getActiveSheet()->setCellValue('J'.$num, $value['total_area']);
            $objPHPExcel->getActiveSheet()->setCellValue('K'.$num, $value['rent_area']);
            ++$num;
        }

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename='.$fileName.'.xls');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    /**
     * 获取缴款通知单
     * @date   2017-6-13
     * @author wuhao
     *
     * @param  string $ordernum     合同编号
     * @param  int    $beginCycle   开始周期20150514
     * @param  int    $endCycle     结束周期20150514
     * @param  int    $type         类别 1=交款通知单 2=收据
     *
     * @return json
     */
    public function getPayNote()
    {
        $ordernum      = I('post.ordernum', '', 'strval');
        $beginCycle    = I('post.begin_cycle', '', 'strval');
        $endCycle      = I('post.end_cycle', '', 'strval');
        $type          = I('post.type', 1, 'intval');
        //$ordernum='149500801179';$beginCycle='20170615';$endCycle='20170714';$type=2;
        $billModel = new BillManager();
        if ($type == 2) {//收据要判断是否已经交过钱
            $payState = $billModel->payBillStatus($ordernum, $beginCycle, $endCycle);
            if ($payState['status'] == 0) {
                $this->apiReturn(400, [], '账单还未结算');
            }
        }
        //$ordernum='149502417442';$beginCycle=$endCycle='20170504';
        if (!$ordernum || !$beginCycle || !$endCycle) {
            $this->apiReturn(400, [], '缺少参数');
        }

        $billInfo = $billModel->getPayBillList(['ordernum' => $ordernum, 'begin_cycle'=> $beginCycle, 'end_cycle'=> $endCycle, 'is_delete'=>0],
            'money, type_money, tenant_id, owner_id, building_id, pay_time');
        if (!$billInfo) {
            $this->apiReturn(400, [], '查不到账单');
        }
        $tenantId = $billInfo[0]['tenant_id'];
        $buildingId = $billInfo[0]['building_id'];
        //获取租户姓名
        $memberModel = new Member();
        $tenantName = $memberModel->getMemberName($tenantId);

        $buildingName = $houseInfo = '';
        //获取楼宇名称
        $buildModel = new Building();
        $buildingName = $buildModel->getBuildingName($buildingId);
        $buildingName = $buildingName ? $buildingName['name'] : '';
        //获取合同对应的房源信息
        $leaseModel = new Lease();
        $houseNumber = $leaseModel->getLeaseExtByOrderNum($ordernum, 'house_number, number, room');
        if ($houseNumber) {
            //查找对应的楼栋和房号
            foreach ($houseNumber as $h) {
                $houseInfo .= $h['number'].'#'.$h['room'].',';
            }
        }
        $hInfo = rtrim($buildingName.$houseInfo,',');

        $rent = $property = $gt = $other = $waterMoney = $powerMoney = $rentf = 0;
        $water = $power = [];
        $waterPowerModel = new WaterPower();
        foreach ($billInfo as $bill) {
            if ($bill['type_money'] == 1) {//房租
                $rent += yuan($bill['money']);
                $rentf += $bill['money'];
            } elseif ($bill['type_money'] == 2) {//物业
                $property += yuan($bill['money']);
            } elseif ($bill['type_money'] == 5 || $bill['type_money'] == 6) {//公摊
                $gt += yuan($bill['money']);
            } elseif ($bill['type_money'] == 3) {//水
                $res = $waterPowerModel->getInfo($ordernum, $beginCycle, $endCycle, $bill['type_money']);
                if ($res) {
                    $water = ['last' => yuan($res['last']), 'this' => yuan($res['this']), 'actual' => yuan($res['actual']), 'money' => yuan($bill['money'])];
                    $waterMoney = yuan($bill['money']);
                } else {
                    $water = ['last' => '', 'this' => '', 'actual' => '', 'money' => yuan($bill['money'])];
                    $waterMoney = yuan($bill['money']);
                }
            } elseif ($bill['type_money'] == 4) {//电
                $res1 = $waterPowerModel->getInfo($ordernum, $beginCycle, $endCycle, $bill['type_money']);
                if ($res1) {
                    $power = ['last' => yuan($res1['last']), 'this' => yuan($res1['this']), 'actual' => yuan($res1['actual']), 'money' => yuan($bill['money'])];
                    $powerMoney = yuan($bill['money']);
                } else {
                    $power = ['last' => '', 'this' => '', 'actual' => '', 'money' => yuan($bill['money'])];
                    $powerMoney = yuan($bill['money']);
                }
            } elseif ($bill['type_money'] == 8) {//其他
                $other += yuan($bill['money']);
            }
        }

        $comment = [];
        if ($type == 2) {//收据还需获取备注
            $commentRes = $billModel->getPayBillComment($ordernum, $beginCycle, $endCycle);
            if ($commentRes) {
                $comment = array_column($commentRes, 'comment');
            }
        }
        $totalMoney =  $rent + $property + $gt + $other + $waterMoney + $powerMoney;
        $data = [
            'house_info'  => $hInfo,
            'tenant_name' => $tenantName['nickname'],
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'rent'        => $rent,
            'property'    => $property,
            'water'       => $water,
            'power'       => $power,
            'gt'          => $gt,
            'other'       => $other,
            'pay_time'    => $billInfo[0]['pay_time'],
            'comment'     => $comment,
            'total'       => $totalMoney
        ];
        $this->apiReturn(200, $data, '');
    }
}
